package com.yanglei.server;

import java.awt.Color;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.JOptionPane;

import com.yanglei.util.XMLUtil;

public class ServerConnection extends Thread {

	private ServerSocket serversocket;

	private Socket socket;

	private Server server;
	
	private ServerMessageThread serverMessageThread;
	
	

	public ServerMessageThread getServerMessageThread() {
		return serverMessageThread;
	}

	public ServerConnection(Server server, int port) {
		try {
			this.server = server;

			this.serversocket = new ServerSocket(port);

			// 服务器启动后执行下面这段代码
			this.server.getJlabel2().setText("运行");

			this.server.getJlabel2().setForeground(new Color(204, 0, 51));

			this.server.getJbutton().setText("运行中");

			this.server.getJbutton().setEnabled(false);

		} catch (Exception e) {
			e.printStackTrace();

			JOptionPane.showMessageDialog(this.server, "端口号被占用", "警告",
					JOptionPane.WARNING_MESSAGE);
		}
	}

	@Override
	public void run() {

		while (true) {
			try {

				socket = this.serversocket.accept();

				InputStream is = socket.getInputStream();

				OutputStream os = socket.getOutputStream();

				byte[] buf = new byte[5000];
				int length = is.read(buf);

				// 客舳税l淼倪B接信息
				String loginXML = new String(buf, 0, length);

				// 从客户端登陆数据中提取出用户名信息
				String username = XMLUtil.extractUsername(loginXML);

				// 判断用户名是否重复
				String loginResult = null;

				// 判断用户是否登陆成功
				boolean isLogin = false;

				if (this.server.getMap().containsKey(username)) {
					loginResult = "failue";
				} else {
					loginResult = "success";

					isLogin = true;

				}

				String xml = XMLUtil.constructLoginResultXML(loginResult);

				os.write(xml.getBytes());

				// 如果用户登陆成功 启动线程
				if (isLogin) {
					this.serverMessageThread = new ServerMessageThread(
							server, socket);
					// 将用户名及与其对应的线程对象放到map当中
					this.server.getMap().put(username, this.serverMessageThread);

					//更新在线用户列表
					this.serverMessageThread.updateUserList();

					this.serverMessageThread.start();
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
